package com.android.application;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;
import java.lang.reflect.Field;

import android.os.Build;


public class WkaUncaughtException implements UncaughtExceptionHandler {

	public void uncaughtException(Thread arg0, Throwable arg1) {
		StringBuffer buf = new StringBuffer();
		//version
		
		//machine
		buf.append("-----------Machine Info-----------/r/n");
		buf.append(getMobileInfo());
		//error info
		buf.append("-----------StackTrace-------------/r/n");
		buf.append(getErrorInfo(arg1));
		
		byte[] logbytes = null;
		try {
			logbytes = buf.toString().getBytes("UTF-8");
		} catch(Exception e) {	}
		if(logbytes != null) {
			BinaryIOUtil.SaveFile(logbytes);
		}
		//kill current process
		android.os.Process.killProcess(android.os.Process.myPid());
	}
	
	private String getErrorInfo(Throwable arg1) {
		Writer writer = new StringWriter();
		PrintWriter pw = new PrintWriter(writer);
		arg1.printStackTrace(pw);
		pw.close();
		String error= writer.toString();
		return error;
	}
	
	private String getMobileInfo() {
		StringBuffer sb = new StringBuffer();
		//通过反射获取系统的硬件信息
		try {
			Field[] fields = Build.class.getDeclaredFields();
			for(Field field: fields){
				//暴力反射 ,获取私有的信息
				field.setAccessible(true);
				String name = field.getName();
				String value = field.get(null).toString();
				sb.append(name+"="+value);
				sb.append("\r\n");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sb.toString();
	}

}
